package com.rural.bus.driver;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.rural.bus.driver.config.MyPreferenceManager;
import com.rural.bus.driver.config.PreferenceKey;
import com.rural.bus.driver.fragment.MyOrderFragment;
import com.rural.bus.driver.model.Order;
import com.rural.bus.driver.net.MyHttpUtil;
import com.rural.bus.driver.net.OnNetCallback;
import com.rural.bus.driver.net.Url;
import com.rural.bus.driver.utils.CommonTools;
import com.rural.bus.driver.utils.DateUtil;
import com.rural.bus.driver.utils.ProgressUtil;
import com.rural.bus.driver.view.CircleImageView;
import com.rural.bus.driver.view.CommonAlertDialog;
import com.rural.bus.driver.view.CommonAlertDialog.OnDialogDismissListener;

public class OrderDealActivity extends BaseActivity implements OnClickListener {

	private static final int SET_NAVIGATION_DISTANCE = 0x91;

	private Button btn_accept_order;
	private CircleImageView iv_passenger_head;
	private TextView tv_passenger_name, tv_order_type, tv_start_time, tv_start_location, tv_end_location, tv_passenger_message, tv_navigation_distance;
	private LinearLayout ll_passenger_message;
	
	private Order order;
	private String userId;
	private double navigateDistance;
	

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SET_NAVIGATION_DISTANCE:
				int distance = msg.arg1;
				if (tv_navigation_distance != null) {
					tv_navigation_distance.setText("全程约 " + distance + " 公里");
				}
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_order_deal);

		initView();
		setListeners();
		initData();
	}

	@Override
	protected void initView() {
		mBtMiddle.setText("订单详情");
		mBtMiddle.setVisibility(View.VISIBLE);
		mBtMiddle.setTextColor(getResources().getColor(R.color.white));

		mImgLeft.setVisibility(View.VISIBLE);
		mImgLeft.setBackgroundResource(R.drawable.back_bg_selector);

		btn_accept_order = (Button) findViewById(R.id.btn_accept_order);
		iv_passenger_head = (CircleImageView) findViewById(R.id.iv_passenger_head);
		tv_passenger_name = (TextView) findViewById(R.id.tv_passenger_name);
		tv_order_type = (TextView) findViewById(R.id.tv_order_type);
		tv_start_time = (TextView) findViewById(R.id.tv_start_time);
		tv_start_location = (TextView) findViewById(R.id.tv_start_location);
		tv_end_location = (TextView) findViewById(R.id.tv_end_location);
		tv_passenger_message = (TextView) findViewById(R.id.tv_passenger_message);
		tv_navigation_distance = (TextView) findViewById(R.id.tv_navigation_distance);
		ll_passenger_message = (LinearLayout) findViewById(R.id.ll_passenger_message);

	}

	@Override
	public void initData() {
		userId = MyApplication.driverInfo.drivId;
		order = (Order) getIntent().getSerializableExtra("order");

		tv_passenger_name.setText("" + order.userName);
		tv_start_time.setText("" + DateUtil.formatDiscriptionTime(order.takeTime));
		
		tv_start_location.setText("" + order.startLocation);
		tv_end_location.setText("" + order.endLocation);
		if (!CommonTools.isEmpty(order.remarks)) {
			ll_passenger_message.setVisibility(View.VISIBLE);
			tv_passenger_message.setText("" + order.remarks);
		}else{
			ll_passenger_message.setVisibility(View.GONE);
		}

		// TYPE0("马上用车", 0),TYPE1("预约用车", 1), TYPE3("全天租", 3), TYPE4("拼车", 4);
		switch (order.orderType) {
		case 0:
			tv_order_type.setText("马上用车");
			break;
		case 1:
			tv_order_type.setText("预约用车");
			break;
		case 3:
			tv_order_type.setText("日租");
			break;
		case 4:
			tv_order_type.setText("拼车");
			break;
		default:
			break;
		}

		caculateNavigateDistance(order);
	}

	@Override
	public void setListeners() {

		mImgLeft.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				OrderDealActivity.this.finish();
			}
		});

		btn_accept_order.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_accept_order:
			acceptOrder();
			break;
		default:
			break;
		}
	}

	private void acceptOrder() {
		MyHttpUtil http = new MyHttpUtil();
		http.addBodyParm("uid", "" + order.userId);
		http.addBodyParm("orderId", "" + order.orderId);
		http.addBodyParm("driverId", "" + userId);
		http.addBodyParm("carType", "" + order.carType);
		http.addBodyParm("orderType", "" + order.orderType);
		http.addBodyParm("number", "" + order.number);
		ProgressUtil.showProgress(this, "");
		http.send(Url.accept_url, new OnNetCallback() {

			@Override
			public void success(JSONObject object) {
				ProgressUtil.closeProgress();

				try {
					if (object.get("status").equals("0")) {
						int callStatus = object.getJSONObject("result").getInt("callStatus");
						if (callStatus == 5) {
							// 订单已取消
							CommonAlertDialog dialog = new CommonAlertDialog(OrderDealActivity.this, "哦", null, "用户已经取消了订单", new OnDialogDismissListener() {

								@Override
								public void onConfirmClicked() {
									Intent intent2 = new Intent(OrderDealActivity.this, MainActivity.class);
									intent2.putExtra("order_id", order.orderId);
									intent2.putExtra("tag", "receive_fail");
									OrderDealActivity.this.startActivity(intent2);
								}

								@Override
								public void onCancelClicked() {
									// TODO Auto-generated method stub

								}
							});
							dialog.show();
						} else if (callStatus == 6) {
							// 订单被别人抢了
							CommonAlertDialog dialog = new CommonAlertDialog(OrderDealActivity.this, "哦", null, "订单被别人抢啦", new OnDialogDismissListener() {

								@Override
								public void onConfirmClicked() {
									Intent intent2 = new Intent(OrderDealActivity.this, MainActivity.class);
									intent2.putExtra("order_id", order.orderId);
									intent2.putExtra("tag", "receive_fail");
									OrderDealActivity.this.startActivity(intent2);
								}

								@Override
								public void onCancelClicked() {
									// TODO Auto-generated method stub

								}
							});
							dialog.show();
						} else if (callStatus == 0) {
							toast("接单成功");
							Intent intent = new Intent(OrderDealActivity.this, MainActivity.class);
							intent.putExtra("order_id", order.orderId);
							intent.putExtra("tag", "accept_order");
							MyOrderFragment.isFresh = true;
							startActivity(intent);
							OrderDealActivity.this.finish();
						} else if(callStatus == 7){
							// 司机账户余额不足
							CommonAlertDialog dialog = new CommonAlertDialog(OrderDealActivity.this, "哦", null, "账户里没钱了,请充值后再来接单", new OnDialogDismissListener() {

								@Override
								public void onConfirmClicked() {
									Intent intent2 = new Intent(OrderDealActivity.this, MainActivity.class);
									intent2.putExtra("order_id", order.orderId);
									intent2.putExtra("tag", "receive_fail");
									OrderDealActivity.this.startActivity(intent2);
								}

								@Override
								public void onCancelClicked() {
									// TODO Auto-generated method stub

								}
							});
							dialog.show();
						}else if(callStatus == 10){
							// 车辆位置不够
							CommonAlertDialog dialog = new CommonAlertDialog(OrderDealActivity.this, "哦", null, "车辆没有足够的位置了！", new OnDialogDismissListener() {

								@Override
								public void onConfirmClicked() {
									Intent intent2 = new Intent(OrderDealActivity.this, MainActivity.class);
									intent2.putExtra("order_id", order.orderId);
									intent2.putExtra("tag", "receive_fail");
									OrderDealActivity.this.startActivity(intent2);
								}

								@Override
								public void onCancelClicked() {
									// TODO Auto-generated method stub

								}
							});
							dialog.show();
						}
						else{
							toast(R.string.data_error);
						}
					} else {
						toast(R.string.data_error);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void fail(String error) {
				ProgressUtil.closeProgress();
				toast("" + error);
			}
		});
	}

	private void caculateNavigateDistance(Order order) {
		RoutePlanSearch routePlanSearch = null;
		if (order != null) {
			routePlanSearch = RoutePlanSearch.newInstance();
			PlanNode startNode = PlanNode.withLocation(new LatLng(order.startLatitude, order.startLongtitude));
			PlanNode endNode = PlanNode.withLocation(new LatLng(order.endLatitude, order.endLongtitude));
			routePlanSearch.setOnGetRoutePlanResultListener(new GetRoutePlanResult(2, mHandler, new LatLng(order.startLatitude, order.startLongtitude), new LatLng(order.endLatitude,
					order.endLongtitude)));
			DrivingRoutePlanOption option = new DrivingRoutePlanOption().from(startNode).to(endNode).policy(DrivingRoutePlanOption.DrivingPolicy.ECAR_TIME_FIRST);
			routePlanSearch.drivingSearch(option);
		}

	}

	public class GetRoutePlanResult implements OnGetRoutePlanResultListener {
		private int id;
		private Handler handler;
		private LatLng mStart;;
		private LatLng mEnd;
		private final String TAG = GetRoutePlanResult.class.getSimpleName();

		public GetRoutePlanResult(int msg, Handler handler, LatLng start, LatLng end) {
			this.id = msg;
			this.handler = handler;
			this.mStart = start;
			this.mEnd = end;
		}

		@Override
		public void onGetDrivingRouteResult(DrivingRouteResult result) {
			if (result != null && result.getRouteLines() != null && result.getRouteLines().size() > 0) {
				if (id == 2) {
					Message msg = handler.obtainMessage();
					msg.what = SET_NAVIGATION_DISTANCE;
					msg.arg1 = (int) Math.ceil(result.getRouteLines().get(0).getDistance() / 1000.f);// 导航距离
					navigateDistance = msg.arg1;
					handler.sendMessage(msg);
				}
			}
		}

		@Override
		public void onGetTransitRouteResult(TransitRouteResult arg0) {

		}

		@Override
		public void onGetWalkingRouteResult(WalkingRouteResult arg0) {

		}
	}
}
